/*************************************************************************
	> File Name: pthread.c
	> Author: Angel Criss
	> Mail: abbytsing@gmail.com 
	> Created Time: 五  7/18 17:01:01 2014
 ************************************************************************/

/*
 * 用两次pthread_create创建两个线程,两个线程都调用func1,并在func1中
 * 创建新的线程并调用func,打印出‘This is ...',调用pthread_exit结束自己 
 * 在func1中执行分离线程的操作(分离后的线程将在主进程退出是被杀死)
 * 所以在ex1中用pthread_join操作等待结束的线程(放一个sleep也行)
 *
 * 可以观察到 线程的竞争现象  :) [多运行几次]
 *
 */

#include<stdlib.h>
#include<stdio.h>
#include<string.h>
#include<unistd.h>
#include<pthread.h>

int place=1;
void *func(void *arg)
{
    char *argv=(char *)arg;
    printf("\n%s\n",argv);
    pthread_exit(arg);
}

void *func1(void *arg1)
{
    
    int out;
    char *len=(char *)arg1;
    pthread_t th;

    if(pthread_equal(th,pthread_self()))
        printf("the are matched\n");
    
    printf("\n%s\n",len);

    printf("*********** %d time(s) call func1 ************\n",place);

    place+=1;

    pthread_create(&th,NULL,func,"\e[32m This invok from func1\e[0m\n");

    out=pthread_detach(th);
    if(out!=0)
    {
        perror("phtread_detach");
        exit(out);
    }
    else
        printf("detach succeeded\n");
    return (void *)(strlen((len)));
}

int main(int argc, char *argv[])
{
    pthread_t th,th1;
    void *res, *res1;
    int ex,ex1;
    
    ex=pthread_create(&th,NULL,func1,"\e[42m <*** 1st pthread ***>\e[0m\n");
    if(ex!=0)
    {
        perror("create");
        exit(1);
    }
    
    ex=pthread_join(th,&res);
    if(ex!=0)
    {
        perror("join");
        exit(1);
    }
    printf("\e[32 pthread_join succeeded\e[0m\n");
    printf("return value is %ld\n",(long)res);

    /*****************************************************/

    printf("\n\e[36manother test\e[0m\n");
    
    /*******************************************************/
    
    ex1=pthread_create(&th1,NULL,func1,"\e[46m<-- creat child pthread done -->\e[0m\n");
    if(ex1!=0)
    {
        perror("create_1");
        exit(1);
    }
    
    ex1=pthread_join(th1,&res1);
    if(ex!=0)
    {
        perror("join_1");
        exit(1);
    }
    printf("\e[32 pthread_join succeeded\e[0m\n");
    printf("return value is %ld\n",(long)res1);

    exit(0);
}
